package com.anlogic.sdk.ui.tests.utils;

import java.util.regex.Pattern;

import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.waits.Conditions;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.waits.ICondition;

import com.anlogic.sdk.ui.tests.utils.ProjectAttributeUtils.ConsoleTextMatches;

public class ProgramFpgaUtils {
	
	public static void programFpga(SWTWorkbenchBot bot,String chip,String connection,String path) {
		bot.waitUntil(Conditions.shellIsActive("data - FutureDynasty"));
		
		bot.menu("Tools").menu("Program FPGA").click();
		bot.comboBox(0).setSelection(chip);
		bot.comboBox(1).setSelection(connection);
		bot.textWithLabel("Bitstream:").setText(path);
		bot.button("Program").click();
		
		SWTBotView consoleView = bot.viewByPartName("Console");
		consoleView.setFocus();
		if (consoleView.isActive()) {
			System.out.println(111);
			Pattern p = Pattern.compile(".*" + "Program fpga success" + ".*", Pattern.DOTALL);

			bot.waitUntil(consoleTextMatches(consoleView, p), 30 * 1000);
		}
		
		
	}
	
	
	protected static ICondition consoleTextMatches(SWTBotView consoleView, Pattern pattern) {
		return new ConsoleTextMatches(consoleView, pattern);
	}

	static class ConsoleTextMatches implements ICondition {
		private final SWTBotView view;
		private Pattern pattern;

		public ConsoleTextMatches(SWTBotView view, Pattern pattern) {
			this.view = view;
			this.pattern = pattern;
		}

		@Override
		public boolean test() {
			if (view.isActive()) {
				String output = view.bot().styledText().getText();
				java.util.regex.Matcher m = pattern.matcher(output);
				return m.matches();
			}
			return false;
		}

		@Override
		public void init(SWTBot bot) {
		}

		@Override
		public String getFailureMessage() {
			return "no matcher agrs";
		}
	}
	

}
